package com.tlgen.tomcat.utils;

import com.google.common.collect.Lists;
import com.tlgen.tomcat.model.RequestMethodAndUrl;

import java.net.URLDecoder;
import java.util.List;

public class StringRequestUtils {

    /**
     * 获取请求方式
     *
     * @param requestLine
     * @return
     */
    public static String getRequestType(String requestLine) {
        String requestType = "";
        if (!requestLine.isEmpty()) {
            requestType = requestLine.substring(0, requestLine.indexOf(" "));
        }
        return requestType;
    }

    /**
     * 获取请求路径 path
     *
     * @param requestLine
     * @return
     */
    public static String getRequestPath(String requestLine) {
        String requestPath = "";
        if (!requestLine.isEmpty()) {
            String[] split = requestLine.split(" ");
            if (split.length > 0) {
                requestPath = split[1];
            }
        }
        return requestPath;
    }

    /**
     * 获取请求版本
     *
     * @param requestLine
     * @return
     */
    public static String getRequestVersion(String requestLine) {
        String requestVersion = "";
        if (!requestLine.isEmpty()) {
            requestVersion = requestLine.substring(requestLine.indexOf("HTTP/") + 5);
        }
        return requestVersion;
    }

    /**
     * 获取 POST、PUT、DELETE 请求中的 form-data 请求参数
     *
     * @param requestLine
     * @return
     */
    public static List<String> getRequestFormDataParam(String requestLine) {
        String[] split = requestLine.split("Content-Disposition: form-data;");
        List<String> stringList = Lists.newArrayList();
        for (String s : split) {
            if (s.indexOf("name=") > 0) {
                String tmp = s.substring(s.indexOf("name=") + "name=".length() + 1);
                String value = tmp.substring(tmp.indexOf("\"") + 1, tmp.indexOf("-")).trim();
                stringList.add(value);
            }
        }
        return stringList;
    }

    /**
     * 获取 GET、DELETE @PathVariable 的参数值
     *
     * @param methodRequestPath
     * @param url
     * @param currentRequestMethodAndUrl
     */
    public static void getPathVariableParam(String methodRequestPath, String url, RequestMethodAndUrl currentRequestMethodAndUrl) {
        String[] split1 = methodRequestPath.split("/");
        String[] split2 = url.split("/");
        List<String> objects = Lists.newArrayList();
        for (int i = 0; i < split2.length; i++) {
            if (split2[i].startsWith("{")) {
                objects.add(split1[i]);
            }
        }
        Object[] args = new Object[objects.size()];
        for (int i = 0; i < objects.size(); i++) {
            args[i] = URLDecoder.decode(objects.get(i));
        }
        currentRequestMethodAndUrl.setArgs(args);
    }

}
